import hashlib
import binascii

fd_file = "/home/luying/uefi_workspace/edk2/Build/OvmfX64/DEBUG_GCC5/FV/OVMF.fd"
fv_file = "/home/luying/uefi_workspace/edk2/Build/OvmfX64/DEBUG_GCC5/FV/DXEFV.Fv"
# {2d50ff90-01eb-0c8d-7c62-4eccbcd18a0b}
gStoredHashFvPpiGuid = b'\x90\xff\x50\x2D\xEB\x01\x8D\x0C\x7C\x62\x4E\xCC\xBC\xD1\x8A\x0B'

def calculate_file_hash(file_path, hash_algorithm="sha256", buffer_size=8192):
    # First hash
    first_hash_object = hashlib.new(hash_algorithm)

    with open(file_path, "rb") as file:
        while True:
            chunk = file.read(buffer_size)
            if not chunk:
                break
            first_hash_object.update(chunk)

    first_file_hash = first_hash_object.hexdigest()
    print(f"The first sha256 hash of the file is: {first_file_hash}")

    # Second hash
    second_hash_algorithm = "sha256"  # Change this to your desired second hash algorithm
    second_hash_object = hashlib.new(second_hash_algorithm)
    second_hash_object.update(bytes.fromhex(first_file_hash))  # Use bytes.fromhex to convert hex to bytes before hashing

    second_file_hash = second_hash_object.hexdigest()
    return second_file_hash



def insert_hash_value(hash_value):
    binary_hash = binascii.unhexlify(hash_value)
    with open(fd_file, 'rb+') as file:
        whole_data = file.read()    
        if gStoredHashFvPpiGuid in whole_data:
            print("find gStoredHashFvPpiGuid success!\n")
            cur_index = 0
            target_index = whole_data[cur_index:].index(gStoredHashFvPpiGuid)
            file.seek(target_index+16)
            file.write(binary_hash)
            print("Insert success")

if __name__ == '__main__':
    hash_value = calculate_file_hash(fv_file)
    print(f"The sha256 hash of DXEFV is: {hash_value}\n")
    #insert_hash_value(hash_value)